<template>
  <div v-loading="loading" class="hello">
    <div v-show="!showShoppingCart">
      <div ref="topRef" class="flex">
        <el-upload
          action="/"
          :on-change="onChange"
          :auto-upload="false"
          :show-file-list="false"
          accept=".xls, .xlsx"
        >
          <el-button type="primary">导入数据库</el-button>
        </el-upload>
        <el-input
          v-model="searchKey"
          placeholder="搜索关键词"
          @input="searchHandle"
        ></el-input>
        <el-button
          type="danger"
          v-if="shoppingCartSku.length > 0 && !showShoppingCart"
          @click="showShoppingCart = true"
        >
          {{ shoppingCartSku.length }}
        </el-button>
      </div>
      <productList
        :listShow="listShow"
        :height="`calc(100% - ${
          $refs.topRef ? $refs.topRef.offsetHeight : 0
        }px)`"
        :shoppingCartSku="shoppingCartSku"
        @add="add"
      />
    </div>

    <div v-show="showShoppingCart" class="shoppingCartSkuBox">
      <div class="center">
        <el-button type="primary" size="small" @click="showShoppingCart = false"
          >返回列表</el-button
        >
        <el-button type="primary" size="small" @click="DownloadExcel"
          >导出购物车</el-button
        >
        <span> 金额合计：{{ money }}</span>
      </div>
      <productList
        :listShow="shoppingCartList"
        :shoppingCartSku="shoppingCartSku"
        :isShopCart="true"
        @add="add"
        @remove="remove"
        @change="change"
      />
      <div>
        <span v-for="item in shoppingCartList" :key="item.sku"
          >{{ item.sku }}:{{ item.num }},</span
        >
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { debounce } from "throttle-debounce";
import * as XLSX from "xlsx";
import { export_json_to_excel } from "../utils/Export2Excel.js";
import productList from "./productList.vue";

export default {
  name: "HelloWorld",
  components: {
    productList,
  },
  data() {
    return {
      loading: false,
      showShoppingCart: false,
      reg1: new RegExp("#", "g"),
      shoppingCartList: [],
      shoppingCartSku: [],
      searchKey: "",
      list: [],
      listShow: [],
    };
  },
  computed: {
    money() {
      let price = 0;
      this.shoppingCartList.forEach((item) => {
        price = price + item.discount_price * item.num;
      });
      price = price * 1.06;
      return price;
    },
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      this.loading = true;
      axios
        .get("http://47.108.50.135:8887/")
        .then((res) => {
          let data = res.data.data.sort((x, y) => y.price - x.price);
          data = data.filter((item) => item.stock);
          data.forEach((item) => {
            item.pic = "https://bullfrog.izehui.com/uploads/product" + item.pic;
            item.discount = item.discount * 10;
          });
          this.list = data;
          this.listShow = data;
          this.getStorageShopCart();
        })
        .catch((error) => {
          this.$message.error(error);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 文件选择回调
    onChange(file, fileList) {
      // 读取数据的方法
      if (!file) {
        // 如果没有文件 - 当然也可以提醒用户弹个警告框 但是基本没有这种情况的出现
        return false;
      } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        // 文件格式的判断
        instance.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        const data = ev.target.result;
        var workbook = XLSX.read(data, {
          type: "binary",
        });
        console.log(workbook.SheetNames);
        // 取第一张表
        const wsname = workbook.SheetNames[0];
        // 生成json表格内容
        let ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
        const stocks = Object.keys(ws[0]).filter(
          (item) => item.indexOf("剩余库存") > -1
        );
        ws = ws.map((item) => {
          return {
            discount_price: item.本次单个产品价格,
            pic: item.图片链接,
            price: item.系统价,
            name: item.产品名称,
            sku: item.SKU码,
            stock: item[stocks[stocks.length - 1]],
            discount: item.本次折扣系数 * 10,
          };
        });
        ws = ws.filter((item) => item.stock);
        ws = ws.sort((x, y) => y.price - x.price);
        this.list = ws;
        this.listShow = ws;
        this.getStorageShopCart();
      };
      // 如果为原生 input 则应是 file[0]
      fileReader.readAsBinaryString(file.raw);
    },
    // 搜索事件
    searchHandle: debounce(350, function (val) {
      if (!val) {
        return (this.listShow = this.list);
      }

      let skus = [];
      // 以#开头则说明搜索的内容为sku，多个sku空格隔开
      if (val.indexOf("#") == 0) {
        skus = val.replace(reg1, "");
        skus = skus.split(" ");
        skus = skus.filter((s) => s);
        if (skus.length === 0) {
          return true;
        }
        this.listShow = this.list.filter((item) => {
          if (skus.length && skus.includes(item.sku)) {
            return true;
          }
          return false;
        });
      } else {
        let keyswords = val.split(" ");
        keyswords = keyswords.filter((s) => s);
        this.listShow = this.list.filter((item) => {
          if (keyswords.some((e) => item.name && item.name.includes(e))) {
            return true;
          }
          return false;
        });
      }
    }),
    change(item) {
      this.setStorageShopCart();
    },
    // 更新购物车到stoage
    setStorageShopCart() {
      const data = {};
      this.shoppingCartList.forEach((item) => {
        data[item.sku] = item.num;
      });
      localStorage.removeItem("shopCart");
      localStorage.setItem("shopCart", JSON.stringify(data));
      if (this.shoppingCartList.length === 0) {
        this.showShoppingCart = false;
      }
    },
    // 从stoage获取购物车
    getStorageShopCart() {
      let data = localStorage.getItem("shopCart");
      if (!data) {
        return false;
      }
      data = JSON.parse(data);
      this.shoppingCartSku = Object.keys(data);

      let shopCartList = this.list.filter((item) =>
        shoppingCartSku.value.includes(item.sku)
      );
      this.shoppingCartSku = shopCartList.map((item) => item.sku);
      shopCartList.forEach((item) => {
        item.num = data[item.sku];
      });
      this.shoppingCartList = shopCartList;
    },
    // 加入购物车
    add(item) {
      if (this.shoppingCartSku.includes(item.sku)) {
        return true;
      }
      this.shoppingCartList.push({ ...item, num: 1 });
      this.shoppingCartSku.push(item.sku);

      this.setStorageShopCart();
    },
    // 删除购物车某一个sku
    remove(item) {
      this.shoppingCartList = this.shoppingCartList.filter(
        (y) => y.sku !== item.sku
      );
      this.shoppingCartSku = this.shoppingCartList.map((y) => y.sku);
      this.setStorageShopCart();
    },
    // 导出excel
    DownloadExcel() {
      const list = this.shoppingCartList;
      const headers = [
        { label: "", prop: "" },
        { label: "SKU码", prop: "sku" },
        { label: "购买数量", prop: "num" },
        { label: "产品名称", prop: "name" },
        { label: "购买价格", prop: "discount_price" },
        { label: "图片链接", prop: "pic" },
      ];

      const tHeader = headers.slice(1).map((item) => {
        return item.label || item.field || item.slotName;
      });

      const filterVal = headers.slice(1).map((item) => {
        return item.prop || item.slotName;
      });
      const data = formatJson(filterVal, list);
      const time = new Date();
      const date =
        time.getFullYear() +
        "-" +
        (time.getMonth() + 1 + "").padStart(2, "0") +
        "-" +
        (time.getDate() + "").padStart(2, "0");
      export_json_to_excel({
        header: tHeader,
        data,
        filename: "姓名" + date,
        bookType: "xlsx",
      });
    },
    // 格式化成二维数据
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
  },
};
</script>

<style scoped>
.hello {
  max-width: 500px;
  margin: 0 auto;
}
.shoppingCartSkuBox {
  width: 100%;
  height: 100%;
}
.flex {
  display: flex;
}
</style>
